<template lang="html">
  <div v-loading="loading" class="main-panel">
    <el-button type="primary" @click="mediaDialog('post')">添加</el-button>
    <el-dialog v-loading="loading" title="编辑" :visible.sync="mediaDiaIsShow" class="diaForm" :append-to-body="false">
      <el-form
        ref="mediaRef"
        :model="mediaForm"
        :rules="mediaRules"
        label-width="140px"
      >
        <!--        <el-form-item label="资源名称" prop="name">-->
        <!--          <el-col :span="15">-->
        <!--            <el-input-->
        <!--              v-model="mediaForm.name"-->
        <!--              type="text"-->
        <!--              placeholder="请输入资源名称"-->
        <!--            />-->
        <!--          </el-col>-->
        <!--        </el-form-item>-->
        <el-form-item label="资源组别" prop="media_group_id">
          <el-col :span="15">
            <el-select
              v-model="mediaForm.media_group_id"
              filterable
              remote
              clearable
              reserve-keyword
              placeholder="请选择资源组别"
              :remote-method="getMediaGroupRemote"
              :loading="loading"
            >
              <el-option
                v-for="item in mediaGroupOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="选取资源" prop="media_id">
          <!--          <el-upload-->
          <!--            ref="upload"-->
          <!--            action=""-->
          <!--            multiple-->
          <!--            :on-preview="handlePictureCardPreview"-->
          <!--            :on-remove="handleRemove"-->
          <!--            list-type="picture"-->
          <!--            :auto-upload="false"-->
          <!--            :on-change="beforeMediaUpload"-->
          <!--          >-->
          <!--            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>-->
          <!--            &lt;!&ndash;            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>&ndash;&gt;-->
          <!--            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
          <!--          </el-upload>-->
          <el-upload
            ref="upload"
            action=""
            multiple
            :on-change="beforeMediaUpload"
            :before-remove="removeMediaUpload"
            :file-list="mediaList"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="editMedia()"
          >确认
          </el-button>
          <el-button @click="mediaDiaIsShow = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-table
      :data="mediaTableData"
      border
      style="width: 100%"
    >
      <el-table-column
        label="预览"
        width="100"
      >
        <template slot-scope="scope">
          <el-image
            style="width: 100%"
            :src="scope.row.savename"
            fit="fit"
            :preview-src-list="[scope.row.savename]"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="filename"
        label="文件名"
      />
      <el-table-column
        prop="groupInfo.name"
        label="媒体分组"
      />
      <el-table-column
        prop="create_time"
        label="创建时间"
      />
      <el-table-column
        prop="update_time"
        label="更新时间"
      />
      <el-table-column
        label="操作"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="mediaDialog('put',scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="deleteMedia(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align:center;margin-top:20px">
      <el-pagination
        :current-page="mediaTableDataPaginateCurrentPage"
        :page-sizes="mediaTableDataPaginateTotalPageSizes"
        :page-size="mediaTableDataPaginateTotalPageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="mediaTableDataPaginateTotal"
        @size-change="mediaTableDataHandleSizeChange"
        @current-change="mediaTableDataHandleCurrentChange"
      >
        <!-- <span>当前{{ mediaTableDataPaginateCurrentPage }}页，</span>
                        <span>共{{ mediaTableDataPaginateLastPage }}页</span> -->
      </el-pagination>
    </div>
    <el-dialog
      title="已存在的图片列表"
      :visible.sync="existedFilesDialogVisible"
      width="30%">
      <span v-for="v in existedFiles" class="block">
        <el-image style="width: 30%; height: 100px" :src="v"></el-image>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="existedFilesDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      mediaGroupSearchForm: {},
      mediaGroupOptions: [],
      mediaSearchForm: {},
      mediaTableData: [],
      mediaTableDataPaginateCurrentPage: 1,
      mediaTableDataPaginateTotal: 1,
      mediaTableDataPaginateLastPage: 1,
      mediaTableDataPaginateTotalPageSize: 10,
      mediaTableDataPaginateTotalPageSizes: [10, 20, 50, 100],
      mediaTab: [],
      mediaEditType: 'post',
      mediaDiaIsShow: false,
      mediaForm: {},
      mediaRules: {
        // name: [{
        //   required: true,
        //   trigger: 'blur'
        // }],
        media_group_id: [{
          required: true,
          trigger: 'blur'
        }]
      },
      mediaUrl: '',
      prepareUploadImages: [],
      mediaListDialogVisible: false,
      mediaListDialogImageUrl: '',
      mediaListDisabled: false,
      mediaList: [],
      existedFilesDialogVisible: false,
      existedFiles: [],
    }
  },
  created() {
    this.getMediaList()
    this.getMediaGroupList(1, 10000)
  },
  methods: {
    getMediaGroupRemote(query) {
      if (query !== '') {
        this.mediaGroupOptions = this.mediaGroupTableData.filter(item => {
          return item.label.toLowerCase()
            .indexOf(query.toLowerCase()) > -1
        })
      } else {
        this.mediaGroupOptions = this.mediaGroupTableData
      }
    },
    getMediaGroupList(page = 1, limit = 10) {
      this.mediaGroupSearchForm.page = page
      this.mediaGroupSearchForm.limit = limit
      this.$store.dispatch('media/getMediaGroupList', this.mediaGroupSearchForm).then((res) => {
        this.mediaGroupTableData = res.data.data
        this.mediaGroupOptions = res.data.data
        this.mediaGroupTableDataPaginateTotal = res.data.total
        this.mediaGroupTableDataPaginateCurrentPage = res.data.current_page
        this.mediaGroupTableDataPaginateLastPage = res.data.last_page
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleMediaSuccess() {

    },
    removeMediaUpload(file, fileList) {
      this.mediaList = this.mediaList.filter(item => item.uid !== file.uid)
    },
    beforeMediaUpload(file, fileList, type) {
      console.log(file, fileList)
      //  限制单张上传，超过限制即覆盖
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }

      //  校验
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
        return false
      }

      const isImage = file.raw.type.includes('image')
      if (!isImage) {
        this.$message.error('上传的格式必须是图片!')
        return false
      }
      //  验证通过之后，将缓存区文件存入上传区文件中
      this.mediaList.push(file.raw)
      // console.log(this.mediaList)
    },
    submitUpload() {
      console.log(this.$refs.upload)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    mediaTableDataHandleSizeChange(val) {
      // 改变每页显示的条数
      this.mediaTableDataPaginateTotalPageSize = val
      this.getMediaList(1, this.mediaTableDataPaginateTotalPageSize)
    },
    mediaTableDataHandleCurrentChange(val) {
      this.mediaTableDataPaginateCurrentPage = val
      this.getMediaList(val, this.mediaTableDataPaginateTotalPageSize)
    },
    getMediaList(page = 1, limit = 10) {
      this.loading = true
      this.mediaSearchForm.page = page
      this.mediaSearchForm.limit = limit
      this.$store.dispatch('media/getMediaList', this.mediaSearchForm).then((res) => {
        this.mediaTableData = res.data.data
        this.mediaTableDataPaginateTotal = res.data.total
        this.mediaTableDataPaginateCurrentPage = res.data.current_page
        this.mediaTableDataPaginateLastPage = res.data.last_page
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    deleteMedia(row) {
      // console.log(row)
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          this.$store.dispatch('media/deleteMedia', { id: row.id }).then((res) => {
            this.getMediaList()
            this.loading = false
            this.mediaDiaIsShow = false
            this.$message({
              type: 'success',
              message: res.msg
            })
          }).catch(() => {
            this.loading = false
            return false
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    editMedia() {
      switch (this.mediaEditType) {
        case 'post':
          this.$refs['mediaRef'].validate((valid) => {
            if (valid) {
              this.loading = true
              this.mediaForm.files = this.mediaList
              console.log(this.mediaForm.files)
              const formdata = new FormData()
              this.mediaList.forEach((item) => {
                formdata.append('files[]', item)
              })
              formdata.append('media_group_id', this.mediaForm.media_group_id)
              console.log(formdata)
              this.$store.dispatch('media/postMedia', formdata).then((res) => {
                this.getMediaList()
                this.mediaForm = {}
                this.loading = false
                this.mediaDiaIsShow = false
                this.$message({
                  type: 'success',
                  message: res.msg
                })
              }).catch((err) => {
                if (err.response.data.data) {
                  this.existedFiles = err.response.data.data
                  this.existedFilesDialogVisible = true
                }
                this.loading = false
              })
            } else {
              return false
            }
          })
          break
        case 'put':
          this.$refs['mediaRef'].validate((valid) => {
            if (valid) {
              this.loading = true
              this.$store.dispatch('media/putMedia', this.mediaForm).then((res) => {
                this.getMediaList()
                this.mediaForm = {}
                this.loading = false
                this.mediaDiaIsShow = false
                this.$message({
                  type: 'success',
                  message: res.msg
                })
              }).catch(() => {
                this.loading = false
              })
            } else {
              return false
            }
          })
          break
      }
    },
    mediaDialog(type, row) {
      this.mediaDiaIsShow = true
      switch (type) {
        case 'post':
          this.mediaEditType = 'post'
          break
        case 'put':
          this.mediaEditType = 'put'
          // 这里一定要使用nextTick的方式赋值，不然会卡住input
          this.$nextTick(() => {
            //   this.$set(this.mediaForm, 'id', row.id)
          })
          break
        default:
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.main-panel {
  padding: 18px;
  font-size: 10px;
}
</style>
